<html>

<head>
    <title>压缩图片</title>
</head>

<body>
    <input id="upfile" type="file" name="" id="">
    <img id="upimg" src="" alt="">
</body>
<script>
    let upfile = document.getElementById('upfile')
    upfile.addEventListener('change', function (o) {
        console.log(this.files)
        let files = this.files
        let file = files[0]

        let fileUrl = getFileURL(file);
        compressionImage(fileUrl, function (base64) {
            document.getElementById('upimg').src = base64
        })
    })

    //生成一个指向file或blod对象的URL
    function getFileURL(file) {
        let url = null;
        if (window.createObjcectURL != undefined) {
            url = window.createOjcectURL(file);
        } else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

    function compressionImage(path, callback, opt) {
        var img = new Image();
        img.src = path;
        img.onload = function () {
            //默认按比例压缩  
            var w = this.width,
                h = this.height;
            var quality = 0.95; // 默认图片质量为0.7  
            console.log(this);
            // if(opt){

            // }

            //生成canvas  
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');

            // 创建属性节点  
            canvas.setAttribute("width", w);
            canvas.setAttribute("height", h);

            ctx.drawImage(this, 0, 0, w, h);
            // quality值越小，所绘制出的图像越模糊  
            var base64 = canvas.toDataURL('image/jpeg', quality);
            console.log(base64);
            // 回调函数返回base64的值  
            callback(base64);
        };
    };
</script>

</html>